class NewsOfferedMaterial < ActiveRecord::Base
  belongs_to :customer_reference, :polymorphic => true
  belongs_to :news_reference, :polymorphic => true
  belongs_to :material
  belongs_to :contact

  #estados
  STATE_READY_TO_SEND  = "state_ready_to_send"
  STATE_ALREADY_SENT   = "state_already_sent"

  def self.exist?(material, contact)
    #lo que hacemos es chequear si ya se le ofrecio al contacto, dejando de lado al cliente (no se detecta que se le haya ofrecido ya al cliente pero con otro contacto)
    if material.nil? || contact.nil?
      return false
    else
      count = NewsOfferedMaterial.count(:conditions => ["material_id = ? and contact_id = ?", material.id, contact.id])
      return count > 0
    end
  end

  def self.send_mails
    puts "---------------------- Arranca el proceso NewsOfferedMaterial.send_mails ----------------------"

    #se agrupa todos los contactos-news que hay disponibles para enviar
    news_group_by_contact_and_news = NewsOfferedMaterial.all(:select => "contact_id, news_reference_type, news_reference_id", :conditions => ["state = ?", NewsOfferedMaterial::STATE_READY_TO_SEND], :group => "contact_id, news_reference_type, news_reference_id", :order => "contact_id, news_reference_type, news_reference_id")
    news_group_by_contact_and_news.each do |n|
      contact = n.contact
      news_letter = n.news_reference

      puts "Le envio al contacto #{contact.first_name} #{contact.last_name} la lista #{news_letter.description}"

      #obtengo todos los materiales para un contacto-news
      materials_to_mail = []
      materials_to_contact = NewsOfferedMaterial.all(:include => :material, :conditions => ["contact_id = ? and news_reference_type = ? and news_reference_id = ? and state = ?", n.contact_id, n.news_reference_type, n.news_reference_id, NewsOfferedMaterial::STATE_READY_TO_SEND])
      materials_to_contact.each do |n1|
        materials_to_mail << n1.material
        n1.state = NewsOfferedMaterial::STATE_ALREADY_SENT
        n1.save
      end

      #envio el mail
      if news_letter.class.to_s == "GeneralNewsLetter"
        ApplicationMailer.deliver_general_news(contact, news_letter, materials_to_mail)
      end
    end
  end
end
